#!/usr/bin/env perl

use strict;
use warnings;

use FindBin;
use File::Path;

refresh_specs();

sub refresh_specs {
    # okay, we are at author side - refresh Synopses
    if (!eval { require LWP; require LWP::Simple; 1 }) {
        warn "LWP or LWP::Simple not installed: $@\n";
        return;
    }

    our $ua;
    LWP::Simple->import('$ua');

    my $BaseURI = 'http://svn.perl.org/perl6/doc/trunk/design/syn';
    my %Spec = qw(
        01 Overview 02 Syntax       03 Operator     04 Block
        05 Rule     06 Subroutine   09 Structure    10 Package
        11 Module   12 Object       13 Overload
    );

    local $| = 1;
    print "==> Refreshing specs from $BaseURI...\n";
    $ua->timeout(10);

    my $request = HTTP::Request->new(HEAD => $BaseURI);
    my $response = $ua->request($request);

    $response->is_success or return;

    $ua->timeout(60);

    my $etags = $response->header('ETag') or return;
    ($etags =~ /(\d+)/) or return;

    my $remote_revision = $1;
    my $local_revision = -1;

    my $logfile = "$FindBin::Bin/.spec-revision";

    if ( open(my $in, $logfile) ) {
        chomp($local_revision = <$in>);
        close $in;
    }

    if ($local_revision == $remote_revision) {
        print "==> No changes.\n";
        return;
    }

    print "==> Synchronizing to revision $remote_revision:\n";

    for my $num (sort keys %Spec) {
        my $file = $Spec{$num};
        print "  $num --> Spec/$file\n";
        use File::Basename;
        my $dir = (dirname(__FILE__) || '.');
        LWP::Simple::mirror(
            "$BaseURI/S$num.pod" => "$FindBin::Bin/$file.pod"
        );
    }

    open my $out, "> $logfile" or return;
    print $out $remote_revision, "\n";
    close $out;
}
